package com.boco.modules.fdoc.web.resident;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;
import com.boco.common.constants.BusinessConstants;
import com.boco.common.enums.ApiStatusEnum;
import com.boco.common.json.BaseJsonVo;
import com.boco.common.persistence.Page;
import com.boco.common.utils.JsonUtils;
import com.boco.common.utils.StringUtils;
import com.boco.common.web.ServletController;
import com.boco.modules.fdoc.model.FamdoctorEntity;
import com.boco.modules.fdoc.model.QueryResidentEntity;
import com.boco.modules.fdoc.model.ResidentEntity;
import com.boco.modules.fdoc.model.SigServicepackEntity;
import com.boco.modules.fdoc.model.UserDocSignEntity;
import com.boco.modules.fdoc.service.ResidentService;
import com.boco.modules.fdoc.service.SigServicepackService;
import com.boco.modules.fdoc.service.SignService;
import com.boco.modules.fdoc.vo.ResidentVo;
import com.boco.modules.fdoc.vo.ServicepackDetailsVo;
import com.boco.modules.fdoc.vo.SigServicepackVo;
@Controller
@RequestMapping(value = "/queryResident")
public class ResidentController extends ServletController {

	@Resource
	ResidentService residentService;

	@Resource
	SigServicepackService sigServicepackService;
	
	@Resource
	SignService signService;

	/* 继承方法主要用于跳转初始化页面 */
	@Override
	@RequestMapping(value = "/addresident.do")
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView("/resident/addresident");
	}

	/**
	 * queryResidentInfo:单纯跳转界面信息
	 */
	@RequestMapping(value = "/residentInfo")
	public ModelAndView queryResidentInfo() {
		return new ModelAndView("/resident/resident");
	}

	/**
	 * 获取已经签约的居民信息
	 */
	@RequestMapping(value = "/queryResidentInfo")
	public ModelAndView queryResidentInfo(HttpServletRequest request,
			HttpServletResponse response, QueryResidentEntity entity) {
		Page<QueryResidentEntity> page = new Page<QueryResidentEntity>(request,
				response);
		try {
			// 获取已签约用户
			page = residentService.getResidentInfoList(page, entity);
			return new ModelAndView("/resident/checkresident")
					.addObject("pageList", page).addObject("page", page)
					.addObject("option", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取居民签约信息失败", e);
			// 返回界面，提示错误信息
			return new ModelAndView("/resident/checkresident").addObject(
					"errorInfo", "获取居民签约信息失败");
		}
	}

	/**
	 * 获取未签约的居民信息
	 */
	@RequestMapping(value = "/querynoResidentInfo")
	public ModelAndView querynoResidentInfo(HttpServletRequest request,
			HttpServletResponse response, QueryResidentEntity entity) {
		Page<QueryResidentEntity> page = new Page<QueryResidentEntity>(request,
				response);
		try {
			// 获取已签约用户
			page = residentService.getResidentNosigInfoList(page, entity);
			return new ModelAndView("/resident/nokresident")
					.addObject("pageList", page).addObject("page", page)
					.addObject("option", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取居民签约信息失败", e);
			// 返回界面，提示错误信息
			return new ModelAndView("/resident/nokresident").addObject(
					"errorInfo", "获取居民签约信息失败");
		}
	}

	/**
	 * 
	 * addMember: 保存新建的居民信息 设置返回为JSON字符串类型
	 */
	@RequestMapping(value = "/addRsident")
	@ResponseBody
	public String addRsident(ResidentEntity residentEntity) {
		try {
			// 设置为手动修改
			residentEntity
					.setStatus(BusinessConstants.RESIDENG_STATUS_SELFUPDATE);
			int returnInt = residentService.addResident(residentEntity);
			if (returnInt == -1) {
				return JsonUtils.getJson(BaseJsonVo.empty(
						ApiStatusEnum.RE_ADD_RESIDENT.getKey(),
						ApiStatusEnum.RE_ADD_RESIDENT.getValue()));
			}
			return JsonUtils.getJson(BaseJsonVo.success(returnInt));
		} catch (Exception e) {
			logger.error("获取居民签约信息失败", e);
			return JsonUtils.getJson(BaseJsonVo.empty(400,
					"添加居民信息失败，失败原因:" + e.getMessage()));
		}

	}

	/* 根据选择的服务包信息获取居民签约的服务包下的详情信息 */
	@RequestMapping(value = "/obtainaServicepckDatias")
	public ModelAndView obtainaServicepckDatias(Integer packId) {
		SigServicepackVo sigServicepack = null;
		List<SigServicepackVo> allDetails = sigServicepackService
				.getAllDetails();
		for (SigServicepackVo sigServicepackVo : allDetails) {
			int id = sigServicepackVo.getId();
			if (id == packId.intValue()) {
				sigServicepack = sigServicepackVo;
				break;
			}
		}
		List<ServicepackDetailsVo> details = new ArrayList<>();
		if (sigServicepack != null) {
			details = sigServicepack.getDetails();
		}
		return new ModelAndView("/resident/servicepackdatis").addObject(
				"pageList", details);
	}

	/** 用户跳转到签约界面 */
	@RequestMapping(value = "/addresidentsing")
	public ModelAndView addresidentsing(@RequestParam String idCard) {
		try {
			// 根据身份证号码获取该人员下管理户主下的所有用户信息
			List<ResidentVo> residenceMember = residentService.getResidentSigninfo(idCard);
			// 循环获取家庭成员判断户主信息
			ResidentVo fresidengVo = null;
			for (ResidentVo residentVo : residenceMember) {
				if(residentVo.getIsheadCard()){
					fresidengVo = residentVo;
				}
			}
			// 获取所有的服务包信息
			List<SigServicepackEntity> allServicepack = sigServicepackService
					.getAll();
			
			//获取所有的家庭医生信息，暂时用于可选
			List<FamdoctorEntity> allFamdoctorInfo = residentService.getAllFamdoctorInfo();
			
			return new ModelAndView("/resident/addresidentsing").addObject(
					"allServicepack", allServicepack).addObject("residenceMember",
							residenceMember).addObject("fresidengVo",
									fresidengVo).addObject("allFamdoctorInfo", allFamdoctorInfo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取居民全月服务包信息失败", e);
			return new ModelAndView("/resident/addresidentsing");
		}
	}
	
	
	/**居民 解除签约 */
	@RequestMapping(value = "/removeSing")
	@ResponseBody
	public String removeSing(@RequestParam String idCard) {
		try {
			UserDocSignEntity  userDocSignEntity  = new  UserDocSignEntity();
			userDocSignEntity.setStatus("2");
			userDocSignEntity.setIdCard(idCard);
			int  result = residentService.remResisingInfo(userDocSignEntity,false);
			return JsonUtils.getJson(BaseJsonVo.success(result));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("居民解约失败", e);
			return JsonUtils.getJson(BaseJsonVo.success(0));
		}
	}
	
	
	/**居民 解除签约 */
	@RequestMapping(value = "/removetoaddSing")
	@ResponseBody
	public String removetoaddSing(@RequestParam String idCard) {
		try {
			UserDocSignEntity  userDocSignEntity  = new  UserDocSignEntity();
			//设置为续约状态
			userDocSignEntity.setStatus("3");
			userDocSignEntity.setIdCard(idCard);
			int  result = residentService.remResisingInfo(userDocSignEntity,true);
			return JsonUtils.getJson(BaseJsonVo.success(result));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("居民续约失败", e);
			return JsonUtils.getJson(BaseJsonVo.success(0));
		}
	}
	
	/*居民签约服务信息保存图片*/
	@RequestMapping(value = "/saveResingImag.do")
	@ResponseBody
	public String saveResingImag(@RequestParam("files")MultipartFile  files , HttpServletRequest request) {
		try {
			StringBuffer sbf  =  new  StringBuffer("");
			//获取解析器  
	        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
	        //判断是否是文件  
	        if(resolver.isMultipart(request)){  
	            //进行转换  
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);  
	            //获取所有文件名称  
	            Iterator<String> it = multiRequest.getFileNames();  
	            //此处需要我们返回文件路径和对应的
	            DateFormat  sdf  =  new SimpleDateFormat("yyyyMMddHHmmss");
	            Date date = new Date();
	            String localPath = request.getSession().getServletContext().getRealPath("upload/img")+"/" + sdf.format(date)+"/";
	            while(it.hasNext()){  
	                //根据文件名称取文件  
	                MultipartFile file1 = multiRequest.getFile(it.next());  
	                String fileName = file1.getOriginalFilename(); 
	            	// 生成jpeg图片
					String headSuffix = StringUtils.getSuffix(fileName); // 获取后缀名
					//获取随机数，防止出现相同的图片名字
					String signImgHeadName = UUID.randomUUID().toString()+ "." + headSuffix; 
	                //获取文件夹路径
	                File headPath = new File(localPath);
	               //判断文件夹是否创建，没有创建则创建新文件夹
	                if(!headPath.exists()){
	                	headPath.mkdirs();
	                }
	                //需要保存的文件详细信息
	                String localPathHead = localPath + signImgHeadName;
	                sbf.append("upload/img/"+ sdf.format(date)+"/"+signImgHeadName+"===");
	                File newFile = new File(localPathHead); 
	                //上传的文件写入到指定的文件中  
	                file1.transferTo(newFile);  
	            }  
	        }  
	        
			return  JsonUtils.getJson(BaseJsonVo.empty(200,sbf.toString().substring(0,  sbf.toString().length()-3)));
		} catch (Exception e) {
			return JsonUtils.getJson(BaseJsonVo.empty(400,
					"上传居民图片合同失败:" + e.getMessage()));
		}
	}
	
	/**居民 解除签约 */
	@RequestMapping(value = "/saveResingService.do")
	@ResponseBody
	public String saveResingService(@RequestBody List<UserDocSignEntity>  listendity) {
		try {
			for (UserDocSignEntity userDocSignEntity : listendity) {
				signService.sign(userDocSignEntity);
			}
			return JsonUtils.getJson(BaseJsonVo.success(1));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("保存居民签约信息失败", e);
			return JsonUtils.getJson(BaseJsonVo.success(0));
		}
	}
	
	
}
